from time import sleep,time,localtime
import zipfile
from pathlib import PureWindowsPath
import os
import datetime
from threading import Thread
import sqlite3
from configparser import ConfigParser

def crezip(dirpath, outFullName):#备份功能函数
        """
        :param dirpath: 目标文件夹路径
        :param outFullName: 压缩文件保存路径+xxxx.zip 
        """
        time1=localtime(time())
        time2="{}-{}-{}_{}点{}分{}秒".format(time1[0],time1[1],time1[2],time1[3],time1[4],time1[5])
        outFullName +='[备份]备份于' + str(time2) + '.zip'
        zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
        for path, dirnames, filenames in os.walk(dirpath):
            # 去掉目标跟路径，只对目标文件夹下边的文件及文件夹进行压缩
            fpath = path.replace(dirpath, '')

            for filename in filenames:
                zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
        zip.close()

#数据库操作
def newID():                                                         #给新任务用户分配ID（数据库内按递增顺序，ID为缺失的第一项，返回ID
    sel = "SELECT id FROM task"
    db = sqlite3.connect('data.db')
    cur = db.cursor()
    cur.execute(sel)
    db.commit()
    a=cur.fetchall()
    cur.close()
    db.close()
    if len(a) == 0:
        return 1
    c=[]
    for i in a:
        i=i[0]
        c.append(i)
    c.sort()
    flag = True
    for i in range(len(c)):
        if c[i]!=1 and flag == True:
            d=1
            flag = False
            break
        elif i!=0:
            if c[i-1]+1 != c[i]:
                flag = False
                d=c[i-1]+1
                break
        else:
            flag = False
            d=c[-1]+1
    return d

def sort2(a):                                         #冒泡排序
    for i in range(len(a)):
        for j in range(i, len(a)):
            if a[i] > a[j]:
                a[i], a[j] = a[j], a[i]
            if len(a)>=2:
                if a[-1] < a[-2]:
                    a[-1],a[-2]=a[-2],a[-1]
    return a

def file_time(filename):
    t = os.path.getmtime(filename)
    return datetime.datetime.fromtimestamp(t)

class run2(Thread):
    def run(self):
        i =0
        ti = 10
        while True:
            i+=1
            sleep(0.2)
            print('---------------------------------------------------------------------------------')
            print('已执行%d次'%i)
            print('---------------------------------------------------------------------------------')
            try:
                a= such()
                if len(a) != 0:
                    run(a)
                    dele(a)
                    sleep(ti)
                else:
                    print('无备份任务')
                    sleep(ti)
            except:
                sleep(ti)


def such():#搜索数据库中已启动的文件
        db = sqlite3.connect('data.db')
        cur = db.cursor()
        cur.execute("SELECT * FROM task where status == '┗|｀O′|┛ 嗷~~'")
        db.commit()
        a = cur.fetchall()
        cur.close()
        db.close()
        sort2(a)
        return a

def run(a):#执行自动备份
        for i in range(len(a)):
            try:
                start = time()
                print(a[i][2],'-->',a[i][3]+'\\'+a[i][1]+'.zip')
                crezip(a[i][2],a[i][3]+'\\'+a[i][1]+'.zip')
                end = time()
                print('---------------------------------------------------------------------------------')
                print('已备份'+a[i][1]+'.zip,共耗时：%s Seconds'%(end-start))
                print('---------------------------------------------------------------------------------')
            except:
                print('---------------------------------------------------------------------------------')
                print('本次{a[i][1]}.zip备份失败，已自动跳过本次备份')
                print('---------------------------------------------------------------------------------')            

def dele(a):#删除多余备份文件
    
        for i in range(len(a)):
            d=[]
            e=[]
            c=0
            b = os.listdir(a[i][3])
            for j in b:
                if a[i][1] in j:
                    c+=1
                    d.append(j)
                    e.append(j)
            for r in range(c):
                print(8888888888888888888888888888888888888)
                if c > a[i][4]:
                    for g in range(len(d)):
                        print(len(d))
                        filetime = file_time(a[i][3]+'\\'+d[g])
                        print(filetime)
                        d[g] = filetime
                        d.sort()
                        print(d)
                    for x in range(len(b)):
                        print(66666666666666666666666666666666666666666)
                        if d[0] == file_time(a[i][3]+'\\'+e[x]):
                            try:
                                os.remove(a[i][3]+'\\'+e[x])
                                c-=1
                                print('---------------------------------------------------------------------------------')
                                print('已删除：',e[x])
                                print('---------------------------------------------------------------------------------')
                                del d[0]
                                break
                            except:
                                c-=1
                                del d[0]
                                print('---------------------------------------------------------------------------------')
                                print(e[x],'删除失败，已删除本次备份。。')
                                print('---------------------------------------------------------------------------------')
                                break
                else:
                    break

run1 = run2()
run1.start()